<template>
    <div>
        <!-- 查询条件开始 -->
        <el-form ref="queryForm" :model="search" :inline="true" label-width="68px">
            <el-form-item label="所属部门" prop="deptId">
                <el-select
                        v-model="search.deptId"
                        placeholder="请选择部门"
                        clearable
                        size="small"
                        style="width:240px">
                    <el-option
                            v-for="dict in deptOptions"
                            :key="dict.deptId"
                            :label="dict.deptName"
                            :value="dict.deptId"/>
                </el-select>
            </el-form-item>
            <el-form-item label="用户姓名" prop="userName">
                <el-input
                        v-model="search.userName"
                        placeholder="请输入用户姓名"
                        clearable
                        size="small"
                        style="width:240px"/>
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
                <el-input
                        v-model="search.phone"
                        placeholder="请输入手机号"
                        clearable
                        size="small"
                        style="width:240px"/>
            </el-form-item>
            <el-form-item label="状态" prop="status">
                <el-select
                        v-model="search.status"
                        placeholder="可用状态"
                        clearable
                        size="small"
                        style="width:240px">
                    <el-option
                            v-for="dict in statusOptions"
                            :key="dict.dictValue"
                            :label="dict.dictLabel"
                            :value="dict.dictValue"/>
                </el-select>
            </el-form-item>
            <el-form-item label="创建时间">
                <el-date-picker
                        v-model="search.dateRange"
                        size="small"
                        style="width:240px"
                        value-format="yyyy-MM-dd"
                        type="daterange"
                        range-separator="-"
                        start-placeholde="开始日期"
                        end-placeholde="结束日期"/>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="searchdata">搜索</el-button>
                <el-button type="primary" icon="el-icon-refresh" size="mini" @click="clearsearch">重置</el-button>
            </el-form-item>
        </el-form>

        <!-- 表格工具按钮开始 -->
        <el-row :gutter="10" style="margin-bottom: 8px;">
            <el-col :span="1.5">
                <el-button type="primary" icon="el-icon-plus" size="mini" @click="addUser">新增</el-button>
            </el-col>
            <el-col :span="1.5">
                <el-button type="danger" icon="el-icon-delete" size="mini" @click="bachDelUser">批量删除</el-button>
            </el-col>
        </el-row>

        <!-- 添加修改弹出层开始 -->
        <el-dialog
                :title="title"
                :visible.sync="dialogVisible"
                width="800px"
                center
                append-to-body>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
                <!-- 头像 -->
                <el-form-item label="头像" prop="picture" label-width="90px" align="center">
                    <el-upload  ref="upload"
                                action="#"
                                :multiple="true"
                                :on-change="fileChange"
                                :on-remove="fileRemove"
                                :auto-upload="false"
                                :on-success="handleAvatarSuccess"
                                :limit="1"
                                list-type="picture" style="border-radius: 50%;margin-left: 0;border: 1px dashed #d9d9d9;width:100px;height:100px">
                        <img v-if="form.picture" :src="form.picture" width="100px" height="100px" style="border-radius: 50%;margin: 0">
                        <i v-else class="el-icon-plus" style="margin-top: 40px"></i>
                    </el-upload>
                    <div style="margin-left: 200px;">
                        <el-button type="primary" size="mini" v-if="isShow" @click="show">提交</el-button>
                    </div>
                </el-form-item>

                <el-row>
                    <el-col :span="12">
                        <el-form-item label="姓名" prop="userName">
                            <el-input v-model="form.userName" style="width:240px" placeholder="请输入用户名称" clearable size="small" />
                        </el-form-item></el-col>
                    <el-col :span="12">
                        <el-form-item label="手机号" prop="phone">
                            <el-input :disabled="disabled" v-model="form.phone" style="width:240px" placeholder="请输入手机号，作为登陆凭证" clearable size="small" />
                        </el-form-item></el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="所属科室" prop="deptId">
                            <el-select
                                    v-model="form.deptId"
                                    placeholder="所属科室"
                                    clearable
                                    size="small"
                                    style="width:240px">
                                <el-option
                                        v-for="d in deptOptions"
                                        :key="d.deptId"
                                        :label="d.deptName"
                                        :value="d.deptId"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="级别" prop="userRank">
                            <el-select
                                    v-model="form.userRank"
                                    placeholder="用户级别"
                                    clearable
                                    size="small"
                                    style="width:240px">
                                <el-option
                                        v-for="d in levelOptions"
                                        :key="d.dictValue"
                                        :label="d.dictLabel"
                                        :value="d.dictValue"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="年龄" prop="age">
                            <el-input-number v-model="form.age" clearable size="small" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="背景" prop="background">
                            <el-select
                                    v-model="form.background"
                                    placeholder="学历"
                                    clearable
                                    size="small"
                                    style="width:240px">
                                <el-option
                                        v-for="d in backgroundOptions"
                                        :key="d.dictValue"
                                        :label="d.dictLabel"
                                        :value="d.dictValue"/>
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="性别" prop="sex">
                            <el-radio-group v-model="form.sex">
                                <el-radio
                                        v-for="d in sexOptions"
                                        :key="d.dictValue"
                                        :label="d.dictValue"
                                        :value="d.dictValue">{{ d.dictLabel }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="状态" prop="status">
                            <el-radio-group v-model="form.status">
                                <el-radio
                                        v-for="dict in statusOptions"
                                        :key="dict.dictValue"
                                        :label="dict.dictValue"
                                        :value="dict.dictValue">{{ dict.dictLabel }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="12">
                        <el-form-item label="是否参与排班" prop="schedulingFlag">
                            <el-radio-group v-model="form.schedulingFlag">
                                <el-radio
                                        v-for="d in schedulingOptions"
                                        :key="d.dictValue"
                                        :label="d.dictValue"
                                        :value="d.dictValue">{{ d.dictLabel }}</el-radio>
                            </el-radio-group>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item label="邮箱" prop="email">
                            <el-input v-model="form.email" style="width:240px" placeholder="请输入用户邮箱" clearable size="small" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row>
                    <el-col :span="24">
                        <el-form-item label="擅长" prop="strong">
                            <el-input v-model="form.strong" type="textarea" placeholder="请输入用户擅长" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="荣誉" prop="honor">
                            <el-input v-model="form.honor" type="textarea" placeholder="请输入用户相关荣誉" />
                        </el-form-item>
                    </el-col>
                    <el-col :span="24">
                        <el-form-item label="简介" prop="introduction">
                            <el-input v-model="form.introduction" type="textarea" placeholder="请输入用户简介" />
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </span>
        </el-dialog>
        <!-- 添加修改弹出层结束 -->
        <!-- 数据表格开始 -->
        <el-table tooltip-effect="dark" style="width: 100%" ref="multipleSelection" border :data="tableData" @selection-change="handleSelectionChangeUser">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column type="expand">
                <template slot-scope="props">
                    <el-form style="margin-left: 20px">
                        <el-form-item label="邮箱">
                            <span>{{ props.row.email }}</span>
                        </el-form-item>
                        <el-form-item label="擅长">
                            <span>{{ props.row.strong }}</span>
                        </el-form-item>
                        <el-form-item label="荣耀">
                            <span>{{ props.row.honor }}</span>
                        </el-form-item>
                        <el-form-item label="简介">
                            <span>{{ props.row.introduction }}</span>
                        </el-form-item>
                    </el-form>
                </template>
            </el-table-column>
            <el-table-column label="用户ID" align="center" prop="userId" />
            <el-table-column label="用户姓名" align="center" prop="userName" />
            <el-table-column label="部门" align="center" prop="deptId" :formatter="deptformat"/>
            <el-table-column label="手机号码【登陆身份】" width="180" align="center" prop="phone" />
            <el-table-column label="性别" align="center" prop="sex"  :formatter="sexformat"/>
            <el-table-column label="年龄" align="center" prop="age" />
            <el-table-column label="是否排班" align="center" prop="schedulingFlag" :formatter="schedulingformat"/>
            <el-table-column label="级别" prop="userRank" align="center"  :formatter="userRankformat"/>
            <el-table-column label="背景" prop="background" align="center" :formatter="backgroundformat"/>
            <el-table-column label="状态" prop="status" align="center" :formatter="statusformat"/>
            <el-table-column label="创建时间" align="center" prop="createTime" width="200" />
            <el-table-column label="操作" align="center" width="250">
                <template slot-scope="scope">
                    <el-button type="text" icon="el-icon-edit" size="mini" @click="updUser(scope.row)">修改</el-button>
                    <el-button v-if="scope.row.userId!=1" type="text" icon="el-icon-delete" size="mini" @click="delUser(scope.row)">删除</el-button>
                    <el-button v-if="scope.row.userId!=1" type="text" icon="el-icon-thumb" size="mini" @click="rolemanage(scope.row)">分配角色</el-button>
                </template>
            </el-table-column>
        </el-table>
        <!-- 数据表格结束 -->

        <!--  分页-->
        <el-pagination
                v-show="page.total>0"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page.current"
                :page-sizes="[4, 5, 6]"
                :page-size="page.size"
                layout="total, sizes, prev, pager, next, jumper"
                :total="page.total">
        </el-pagination>

        <!--分配角色的对话框-->

        <el-dialog
                title="提示"
                :visible.sync="dialogVisiblerole"
                width="50%">
            <el-table
                    ref="roleListTable"
                    border
                    :data="roleTableList"
                    @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55" align="center" />
                <el-table-column label="角色ID" align="center" prop="roleId" />
                <el-table-column label="角色名称" align="center" prop="roleName" />
                <el-table-column label="权限编码" align="center" prop="roleCode" />
                <el-table-column label="备注" align="center" prop="remark" />
                <el-table-column label="创建时间" align="center" prop="createTime" />
            </el-table>
            <span slot="footer" class="dialog-footer">
            <el-button @click="dialogVisiblerole = false">取 消</el-button>
            <el-button type="primary" @click="confirmRole">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>
<style>
    .demo-table-expand {
        font-size: 0;
    }

    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }

    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }
</style>
<script>
    // import qs from 'qs';
    // import axios from 'axios';
    export default {
        data() {
            return {
                isShow:false,
                /* 存放头像 */
                fileList: [],
                //禁用输入框
                disabled:false,
                //部门信息
                deptOptions: [],
                //系统状态信息
                statusOptions: [],
                //背景字典
                backgroundOptions:[],
                //性别字典
                sexOptions:[],
                //级别字典（学历）
                levelOptions:[],
                //排班字典
                schedulingOptions:[],
                //批量删除多选框
                multipleSelection: [],
                //分配角色多选框
                multipleSelectionrole: [],
                //模糊查询
                search: {},
                //分页
                page: {
                    current: 1,
                    size: 4,
                    total: 10
                },
                //员工的信息
                tableData: [],
                //新增/修改用户弹出层
                dialogVisible: false,
                //分配权限弹出层
                dialogVisiblerole:false,
                //分配角色的用户的id
                userId:0,
                //角色信息
                roleTableList:[],
                //用户具有的角色
                userRoles:[],
                //添加修改对话框的标题
                title:'',
                //添加/修改用户表单数据
                form:{},
                //添加表单规则
                rules: {
                    userName: [
                        {required: true, message: '请输入用户名', trigger: 'blur'},
                        {min: 3, max: 5, message: '长度在 3 到 5 个字符', trigger: 'blur'}
                    ], phone: [
                        {required: true, message: '请输入电话号码', trigger: 'blur'},
                        {min: 11, max: 11, message: '请输入11位电话号码', trigger: 'blur'}
                    ]
                }
            }
        },
        methods: {
            /* 头像 */
            //获取图片列表：上传头像时候触发
            fileChange(file, fileList) {
                this.fileList = fileList;
                //console.log("获取多个图片", this.fileList)
                // this.$refs.pictureSubmit.style.display=inline-block;
                this.isShow=true;
            },
            //触发删除列表
            fileRemove(file, fileList) {
                this.fileList = fileList;
                //console.log(this.fileList)
            },
            //上传成功后处理方法
            handleAvatarSuccess(res, file) {
                //URL对象可以通过createObjectURL(any)方法来将任意内容用一个地址来表示
                this.imageUrl = URL.createObjectURL(file.raw);
            },
            //上传头像
            show() {
                let formData = new FormData;
                if (this.fileList.length == 0) {
                    this.$message.error("还没有上传图片")
                    return;
                }
                this.fileList.forEach((File) => {
                    //将图片数据追加到formData中
                    formData.append("file", File.raw)
                })
                this.$axios({  //使用axios发出请求发出请求上传请求
                    method: "post",
                    headers: {
                        'Content-Type': 'multipart/form-data'
                    },
                    url: "http://localhost:86/system/api/user/uploadFile",
                    data: formData
                }).then(res => {
                    if (res.data.msg == "上传头像成功") {
                        this.$message.success(res.data.msg)
                        this.form.picture = res.data.t;
                        this.$refs.upload.clearFiles();
                        this.isShow=false;
                        // console.log(this.form.picture)
                    } else {
                        this.$message.error("上传头像失败")
                    }
                })
            },
            //多选框
            handleSelectionChangeUser(val) {
                this.multipleSelection = val;
            },
            //条件查询、重置数据
            clearsearch() {
                this.search = {};
            },
            //条件查询
            searchdata() {
                this.initUser();
                //查询完成后回到第一页
                this.page.current = 1;
            },
            //每页显示的条数
            handleSizeChange(val) {
                console.log(`每页 ${val} 条`);
                this.page.size = val;
                this.initUser();
            },
            handleCurrentChange(val) {
                console.log(`当前页: ${val}`);
                this.page.current = val;
                this.initUser();
            },
            //添加/修改用户 2、提交表单
            handleSubmit() {
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        this.$axios.post("/system/api/user/saveOrUpdate",this.form).then(r=>{
                            if (r.data.t){
                                this.$message.success(r.data.msg);
                            }else {
                                this.$message.error("操作失败");
                            }
                            this.initUser();
                            this.dialogVisible=false;
                            this.title='';
                            this.form={};
                        })
                    }
                });
            },
            //添加用户 1、关闭表单
            cancel() {
                this.form={};
            },
            //添加用户 1、开启对话框启用添加表单
            addUser() {
                if (this.$refs.form != undefined) {
                    this.$refs.form.clearValidate();
                }
                this.disabled=false;
                this.title="添加用户信息"
                this.dialogVisible = true;
                this.form = {age:0,sex:'2',status:'0'};
            },
            //编辑操作
            updUser(row) {
                if (this.$refs.form != undefined) {
                    this.$refs.form.clearValidate();
                }
                this.title="修改用户信息"
                this.disabled=true;
                this.form = {age:0,sex:'2',status:'0'};
                this.dialogVisible = true;
                this.form = JSON.parse(JSON.stringify(row));
                this.form.userId =row.userId;
            },
            //删除操作
            delUser(row) {
                this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.delete("system/api/user/delUser/"+row.userId).then(r=>{
                        if (r.data.t){
                            this.$message.success(r.data.msg);
                        }else {
                            this.$message.error("删除失败");
                        }
                        this.page.current=1;
                        this.initUser();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //批量删除用户信息
            bachDelUser(){
                //传递哪些参数？userId  roleIds
                let userIds=[];
                this.multipleSelection.forEach(item=>{
                    userIds.push(item.userId);
                })
                this.$confirm('此操作将永久删除该用户信息, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.delete("system/api/user/bachUser/"+userIds).then(r=>{
                        if (r.data.t){
                            this.$message.success(r.data.msg);
                        }else {
                            this.$message.error("删除失败");
                        }
                        this.page.current=1;
                        this.initUser();
                    })
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            },
            //确认分配角色
            confirmRole(){
                //传递哪些参数？userId  roleIds
                let roleIds=[];
                this.multipleSelectionrole.forEach(item=>{
                    roleIds.push(item.roleId);
                })
                this.$axios.post("/system/api/role/confirmRole?roleIds="+roleIds+"&userId="+this.userId).then(result=>{
                    this.dialogVisiblerole=false;
                    this.$message.success("分配角色成功")
                })
            },
            //分配角色弹出
            async rolemanage(row){
                this.userId=row.userId;
                //打开弹出框
                this.dialogVisiblerole=true;
                //查询所有角色
                //当前用户具有的角色
                await this.$axios.get("system/api/role/getByUserId/"+row.userId).then(result=>{
                    this.roleTableList=result.data.t.roles;
                    this.userRoles=result.data.t.userRoles;
                });
                //创建一个空数组用来存放默认数据
                let list = []
                //遍历表格的数据，再遍历需要在表格中反显的数据，两者的id一致
                this.roleTableList.forEach((item) => {
                    this.userRoles.forEach(val => {
                        if (val.roleId=== item.roleId) {
                            // 把判断出来的默认表格数据push到创建的数组中
                            list.push(item)
                        }
                    })
                })
                //再遍历数组，将数据放入方法中
                list.forEach((row) => {
                    this.$refs.roleListTable.toggleRowSelection(row, true)
                })

            },
            //改变后的数据
            handleSelectionChange(v){
                this.multipleSelectionrole=v;
            },
            //加载所有部门
            initDept() {
                this.$axios.get("/system/api/dept/list").then(r => {
                    this.deptOptions = r.data.t;
                })
            },
            //加载系统状态
            initStatus() {
                this.$axios.get("system/api/dict/data/findByType/sys_normal_disable").then(r => {
                    this.statusOptions = r.data.t;
                })
            },
            //加载性别字典
            initSex(){
                this.$axios.get("system/api/dict/data/findByType/sys_user_sex").then(r => {
                    this.sexOptions = r.data.t;
                })
            },
            //加载级别字典
            initLevel(){
                this.$axios.get("system/api/dict/data/findByType/sys_user_level").then(r => {
                    this.levelOptions = r.data.t;
                })
            },
            //加载学历字典
            initBackground(){
                this.$axios.get("system/api/dict/data/findByType/sys_user_background").then(r => {
                    this.backgroundOptions = r.data.t;
                })
            },
            //加载排班字典
            initScheduling(){
                this.$axios.get("system/api/dict/data/findByType/sys_yes_no").then(r => {
                    this.schedulingOptions = r.data.t;
                })
            },
            //背景字典的解析
            backgroundformat(row){
                let val=row.background;
                return this.formatDict(this.backgroundOptions,val)
            },
            //性别字典解析
            sexformat(row){
                let val=row.sex;
                return this.formatDict(this.sexOptions,val)
            },
            //排班字典解析
            schedulingformat(row){
                let val=row.schedulingFlag;
                return this.formatDict(this.schedulingOptions,val)
            },
            //级别字典解析
            userRankformat(row){
                let val=row.userRank;
                return this.formatDict(this.levelOptions,val)
            },
            //状态字典解析
            statusformat(row){
                let val=row.status;
                return this.formatDict(this.statusOptions,val)
            },
            //部门
            deptformat(row){
                let val=row.deptId;
                for(let i=0;i<this.deptOptions.length;i++){
                    if(this.deptOptions[i].deptId==val){
                        return this.deptOptions[i].deptName;
                    }
                }
                return "";
            },
            //加载员工信息
            initUser() {
                const newparam = Object.assign(this.search, this.page);
                this.$axios.post("system/api/user/searchUser", newparam).then(r => {
                    this.tableData = r.data.t.records;
                    this.page.total = r.data.t.total;
                })
            }
        },
        created() {
            //加载所有部门
            this.initDept();
            //加载系统状态
            this.initStatus();
            //加载员工信息
            this.initUser();
            //加载性别字典
            this.initSex();
            //加载级别字典
            this.initLevel();
            //加载学历字典
            this.initBackground();
            //加载排班字典
            this.initScheduling();
        }
    }
</script>
